INSERT INTO events VALUES (event_id_seq.NEXTVAL, 'Writing off', 1);
INSERT INTO events VALUES (event_id_seq.NEXTVAL, 'Writing off', 2);
INSERT INTO events VALUES (event_id_seq.NEXTVAL, 'Writing off', 3);

SELECT p.place_name, SUM(h.quantity) AS "Devices to be written off"
FROM history h, places p, events e, devices d WHERE h.device_id = d.device_id AND h.event_id = e.event_id
AND e.place_id = p.place_id AND d.bandwidth <= 10
GROUP BY p.place_name;

INSERT INTO history
SELECT history_id_seq.NEXTVAL, (SELECT MAX(event_date) FROM history) + 30, h.device_id, h.quantity, 4 FROM history h, devices d
WHERE h.event_id = 1 AND h.device_id = d.device_id AND d.bandwidth <= 10;

INSERT INTO history
SELECT history_id_seq.NEXTVAL, (SELECT MAX(event_date) FROM history) + 30, h.device_id, h.quantity, 5 FROM history h, devices d
WHERE h.event_id = 2 AND h.device_id = d.device_id AND d.bandwidth <= 10;

INSERT INTO history
SELECT history_id_seq.NEXTVAL, (SELECT MAX(event_date) FROM history) + 30, h.device_id, h.quantity, 6 FROM history h, devices d
WHERE h.event_id = 3 AND h.device_id = d.device_id AND d.bandwidth <= 10;

INSERT INTO history
SELECT history_id_seq.NEXTVAL, p1, p2, p3, p4 FROM
(SELECT MAX(d) - 7 p1, 4 p2, SUM(total_ports) * 2 / devices.ports_number p3, 1 p4 FROM
(SELECT event_date d, quantity * ports_number total_ports FROM history, devices
WHERE event_id = 5 AND history.device_id = devices.device_id) tmp, devices
WHERE device_id = 4
GROUP BY devices.ports_number);

INSERT INTO history
SELECT history_id_seq.NEXTVAL, p1, p2, p3, p4 FROM
(SELECT MAX(d) - 7 p1, 4 p2, SUM(total_ports) * 2 / devices.ports_number p3, 1 p4 FROM
(SELECT event_date d, quantity * ports_number total_ports FROM history, devices
WHERE event_id = 6 AND history.device_id = devices.device_id) tmp, devices
WHERE device_id = 4
GROUP BY devices.ports_number);

INSERT INTO history
SELECT history_id_seq.NEXTVAL, event_date + 6, device_id, quantity, 2 FROM history
WHERE event_id = 1 AND event_date = (SELECT MAX(event_date) - 7 FROM history WHERE event_id = 5);

INSERT INTO history
SELECT history_id_seq.NEXTVAL, event_date + 6, device_id, quantity, 3 FROM history
WHERE event_id = 1 AND event_date = (SELECT MAX(event_date) - 7 FROM history WHERE event_id = 6);

COMMIT;